<!--
* @Author: zeng_ze
* @Date: 2019-11-7
* @Description: 人员管理
-->
<template>
  <div class="people-container">
    <div class="left-container">
      <div class="resize-bar-vertical" />
      <div class="resize-line-vertical" />
      <div class="left-top-content">
        <div style="position: relative; height: 100%">
          <fks-input
            v-model="filterText"
            :placeholder="LANG.INPUT_CATEGORY"
            clearable
            maxlength="50"
            class="search-input"
            suffix-icon="fks-icon-search"
            style="margin-bottom: 16px"
          />
          <fks-tree
            ref="tree"
            show-icon
            class="filter-tree"
            :data="orgListData"
            node-key="id"
            highlight-current
            :default-expanded-keys="defaltExpand"
            :check-on-click-node="true"
            :filter-node-method="filterNode"
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
          >
            <div
              slot-scope="{ data }"
              class="fks-tree-node__label"
              style="word-spacing: 2px"
            >
              {{ data.content.name }}{{ '\xa0' }}({{ data.content.memberNum }})
            </div>
          </fks-tree>
        </div>
      </div>
    </div>
    <div class="right-container">
      <fks-query-page
        v-loading="listLoading"
        :data="tableData"
        :total="total"
        :page-size.sync="pageSize"
        :current-page.sync="currentPage"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[20, 50, 100]"
        :element-loading-text="LANG.LOADING"
        :table-name="LANG.STAFF_LIST"
        @query="searchUser"
        @sort-change="sortHandler"
      >
        <template slot="singleSearch">
          <div class="single-searchBox">
            <fks-input
              v-model="searchValue"
              maxlength="50"
              :placeholder="LANG.INPUT_NAME"
              class="single-searchBox-item"
              clearable
              @clear="search"
              @keyup.enter.native="search"
            >
              <fks-button
                slot="append"
                icon="fks-icon-search"
                @click="search"
              />
            </fks-input>
            <fks-button
              v-saas:user="['main', 'notSaas']"
              v-permission="['staff:import']"
              @click="importData"
            >
              <i class="fks-icon-import" />
              <span>{{ LANG.IMPORT }}</span>
            </fks-button>
            <fks-button
              v-permission="['staff:export']"
              @click="exportPeople"
            >
              <i class="fks-icon-export" />
              <span style="margin-left: 8px">{{ LANG.EXPORT }}</span>
            </fks-button>
            <fks-button
              v-permission="['staff:add']"
              v-saas:user="['main', 'notSaas']"
              icon="fks-icon-plus"
              type="primary"
              @click="add"
            >
              <span>{{ LANG.ADD }}</span>
            </fks-button>
          </div>
        </template>
        <template>
          <fks-table-column
            type="index"
            align="center"
            label="#"
          >
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </fks-table-column>
          <fks-table-column
            prop="userFullname"
            :label="LANG.USER_FULL_NAME"
            sortable="custom"
            min-width="60"
            is-link
            @link="viewClick"
          />
          <fks-table-column
            prop="sex"
            :label="LANG.SEX"
            min-width="40"
            sortable="custom"
          >
            <template slot-scope="scope">
              {{ scope.row.sex }}
            </template>
          </fks-table-column>
          <fks-table-column
            prop="orgName"
            :label="LANG.DEPARTMENT"
            align="left"
            min-width="150px"
            :formatter="orgFormat"
          />
          <fks-table-column
            prop="phone"
            :label="LANG.MOBILE"
            min-width="60"
          />
          <fks-table-column
            prop="email"
            :label="LANG.EMAIL"
            min-width="100"
          />
          <fks-table-column
            v-if="saasPermission(['main', 'notSaas'], 'user')"
            :label="LANG.OPERATION"
            width="100"
            align="left"
          >
            <template slot-scope="scope">
              <fks-button
                v-permission="['staff:edit']"
                type="text"
                @click="editClick(scope.row)"
              >
                {{ LANG.EDIT }}
              </fks-button>

              <fks-button
                v-permission="['staff:delete']"
                style="margin-left: 8px"
                class="danger-button"
                danger-text
                @click="deleteHandler(scope.row)"
              >
                {{ LANG.DELETE }}
              </fks-button>
            </template>
          </fks-table-column>
        </template>
      </fks-query-page>
    </div>
    <staff-info
      :people-type="peopleTitle"
      :people-data="peopleData"
      :visible.sync="peopleVisible"
      @searchUser="searchUser"
    />
    <import-user
      :visible.sync="importVisible"
      :flag="importFlag"
      @fetchData="getAllOrg"
    />
  </div>
</template>

<script>
import { exportFile } from '@/utils/file'
import Mix from '@/mixins/module'
import * as User from './api'
import { getUserInfo } from '@/api/user'
import * as types from '@/store/Getter/getterTypes.js'
import StaffInfo from './StaffInfo/index'
import { Multipane, MultipaneResizer } from 'vue-multipane'
import importUser from '@/modules/System/User/Import'
export default {
  name: 'Staff',
  components: {
    StaffInfo,
    Multipane,
    MultipaneResizer,
    importUser
  },
  mixins: [Mix],
  data() {
    return {
      importFlag: 'people',
      importVisible: false,
      peopleVisible: false,
      peopleData: {},
      orgName: '',
      orgData: {},
      orgVisible: true,
      importVisible: false,
      peopleTitle: 'add',
      orgList: [],
      topNode: '', //顶层组织机构id
      defaltExpand: [], //默认展开组织机构节点id
      filterText: '', //组织机构树检索内容
      transitions: true, //禁用tag渐变动画
      searchValue: '', //搜索框搜索内容绑定字段
      exportOrgNo: '', //导出人员所属组织机构ID
      listLoading: false, //数据获取时的加载
      tableData: [], //表格数据源
      //新增用户、编辑用户弹窗 显隐
      pageSize: 20,
      sort: '',
      columnName: '',
      deleteFlag: '',
      data: '',
      aPost: '',
      total: 0,
      currentPage: 1,
      row: {},
      number: 0,
      exportAll: true
    }
  },
  computed: {
    portalId() {
      return this.$store.state.portal.id
    },
    multiPortal() {
      return this.$store.getters[types.MULTI_PORTAL]
    },
    orgListData() {
      return [
        ...this.orgList,
        {
          content: {
            name: this.LANG.TO_BE_DISTRIBUTED,
            orgNo: '-2',
            memberNum: this.number
          }
        }
      ]
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    this.getAllOrg()
    this.getData(
      {
        pageNo: 1,
        pageSize: 20,
        portalId: this.portalId,
        accountStatus: 1,
        noOrg: true
      },
      true
    )
  },
  methods: {
    importData() {
      this.importVisible = true
    },
    orgFormat(row, column, cellValue) {
      if (!row.orgList) {
        return ''
      }
      let orgDataList = []
      orgDataList = row.orgList.map((item) => {
        return item.name
      })
      return orgDataList.toString()
    },
    //打开添加人员弹窗
    openDialog() {
      this.importVisible = true
    },
    //导出人员信息
    exportPeople() {
      let excelExportLikeParam = {}
      if (this.exportAll) {
        excelExportLikeParam.exportAll = true
      } else {
        if (this.exportOrgNo) {
          if (this.exportOrgNo == '-2') {
            excelExportLikeParam.filterNoOrg = true
          } else {
            excelExportLikeParam.orgNo = this.exportOrgNo
            excelExportLikeParam.filterHaveOrg = true
          }
        } else {
          excelExportLikeParam.filterHaveOrg = true
          excelExportLikeParam.orgNo = this.orgNo
        }
      }
      excelExportLikeParam.portalId = this.portalId
      excelExportLikeParam.accountStatus = 1
      User.exportPeople(excelExportLikeParam)
        .then((res) => {
          if (res.request.response.type == 'application/json') {
            let fileReader = new FileReader()
            fileReader.readAsText(res.data)
            let that = this
            fileReader.onload = function (result) {
              let jsondata = JSON.parse(result.target.result)
              if (jsondata.status) {
                that.$message.success(that.LANG.EXPORT_SUCCESS)
              } else {
                that.$message.error(that.LANG.EXPORT_FAILED)
              }
            }
          } else {
            // 'application/vnd.ms-excel'
            exportFile(res)
            this.$message.success(this.LANG.EXPORT_SUCCESS)
          }
        })
        .catch(() => {})
    },
    //对树形节点内容进行筛选
    filterNode(value, data) {
      if (!value) return true
      return data.content.name.indexOf(value) !== -1
    },
    //列表排序方法
    sortHandler(data) {
      let params = {
        orgNo: this.orgNo == '-2' ? '' : this.orgNo,
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        portalId: this.portalId,
        accountStatus: '1',
        searchValue: this.searchValue
      }
      if (!data.order) {
        this.sort = ''
        this.columnName = ''
      } else {
        this.sort = data.order === 'ascending' ? 'asc' : 'desc'
        this.columnName = data.prop === 'userFullname' ? 'user_fullname' : 'sex'
      }
      params.sort = this.sort
      params.columnName = this.columnName
      if (this.orgNo == '-2') {
        params.noOrg = true
      }
      this.getData(params)
    },
    //点击左侧树节点的回调
    handleNodeClick(data) {
      this.exportAll = false
      if (data.content.orgNo == '-2') {
        this.orgVisible = false
      } else {
        this.orgVisible = true
      }
      this.orgName = data.content.name
      this.orgData = data
      this.currentPage = 1
      this.orgNo = data.content.orgNo
      this.exportOrgNo = data.content.orgNo
      this.searchUser()
    },
    //打开新增人员弹窗
    add() {
      this.peopleVisible = true
      this.peopleData = {}
      this.peopleTitle = 'add'
    },
    //打开查看人员信息弹窗
    viewClick({ row }) {
      this.peopleTitle = 'view'
      getUserInfo({
        userName: row.userName,
        portalId: this.portalId
      })
        .then((res) => {
          if (res.status && res.data) {
            this.aPost = res.data.postList.map((item) => {
              return item.id
            })
            this.photoToken = res.data.photoToken
            this.row = Object.assign(
              row,
              { postList: this.aPost },
              { photoToken: this.photoToken }
            )
            this.peopleData = JSON.parse(JSON.stringify(row))
            this.peopleVisible = true
          }
        })
        .catch(() => {
          this.aPost = []
        })
    },
    //打开编辑人员弹窗
    editClick(row) {
      this.peopleTitle = 'edit'
      getUserInfo({
        userName: row.userName,
        portalId: this.portalId
      })
        .then((res) => {
          if (res.status && res.data) {
            this.aPost = res.data.postList.map((item) => {
              return item.id
            })
            this.photoToken = res.data.photoToken
            this.row = Object.assign(
              row,
              { postList: this.aPost },
              { photoToken: this.photoToken }
            )
            this.peopleData = JSON.parse(JSON.stringify(row))
            this.peopleVisible = true
          }
        })
        .catch(() => {
          this.aPost = []
        })
    },
    //清空搜索内容获取人员数据
    search() {
      this.currentPage = 1
      this.searchUser()
    },
    //搜索人员
    searchUser() {
      if (!this.orgNo) {
        this.orgNo = '-2'
      }
      let params = {
        orgNo: this.orgNo == '-2' ? '' : this.orgNo,
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        portalId: this.portalId,
        sort: this.sort,
        accountStatus: '1',
        columnName: this.columnName,
        searchValue: this.searchValue
      }
      if (this.orgNo == '-2') {
        params.noOrg = true
      }
      this.getData(params)
    },
    //获取人员列表数据
    @permission('staff:query')
    getData(data, initFlag) {
      this.listLoading = true
      User.getUsers(data)
        .then((res) => {
          this.listLoading = false
          if (res.status) {
            if (!data.orgNo && initFlag) {
              this.number = res.data.total
              return
            }
            this.deleteFlag = res.data.size
            this.tableData = res.data.list
            this.total = res.data.total
          }
        })
        .catch(() => {
          this.listLoading = false
          this.tableData = []
        })
    },
    deleteHandler(row) {
      this.$confirm(this.LANG.DELETE_CONFIRM, {
        title: this.LANG.TIPS,
        type: 'warning',
        confirmButtonText: this.LANG.DELETE,
        cancelButtonText: this.LANG.CANCEL,
        confirmButtonClass: 'fks-button--danger',
        deleteMode: true
      })
        .then(() => {
          if (this.multiPortal) {
            this.deleteClick(row)
          } else {
            this.logOffUser(row)
          }
        })
        .catch(() => {})
    },
    //从门户中删除人员
    deleteClick(row) {
      User.updatePortal({
        id: this.portalId,
        deleteUserIdList: row.id.split(',')
      })
        .then((response) => {
          if (response.status) {
            this.$message.success(this.LANG.DELETE_SUCCESS)
            if (this.deleteFlag == '1') {
              this.currentPage = 1
            }
            this.searchUser()
          }
        })
        .catch(() => {})
    },
    logOffUser(row) {
      User.editUsers(
        JSON.stringify({
          userName: row.userName,
          id: row.id,
          accountStatus: 3
        })
      )
        .then((response) => {
          if (response.status) {
            this.$message.success(this.LANG.DELETE_SUCCESS)
            this.searchUser()
          }
        })
        .catch(() => {})
    },
    //获取组织机构数据
    @permission('staff:dept')
    getAllOrg() {
      this.listLoading = true
      User.getOrg(this.portalId)
        .then((res) => {
          if (res.status) {
            if (res.data[0]) {
              this.topNode = res.data[0].id
              this.orgNo = res.data[0].id
              this.orgName = res.data[0].content.name
              this.defaltExpand.push(res.data[0].id)
              this.orgData = res.data[0]
              this.orgVisible = true
            } else {
              this.orgVisible = false
            }
            this.orgList = res.data
          }
          this.searchUser()
        })
        .catch(() => {
          this.listLoading = false
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.people-container {
  display: flex;
  overflow: hidden;
  height: 100%;
  .left-container {
    height: 100%;
    position: relative;
    .resize-bar-vertical {
      height: inherit;
      resize: horizontal;
      opacity: 0;
      cursor: col-resize;
      width: 300px;
      min-width: 300px; /* 最小宽度 300px */
      max-width: 600px; /* 最大宽度 600px */
      overflow: scroll;
      z-index: -100 !important;
    }
    .resize-line-vertical {
      position: absolute;
      right: 5px;
      top: 0;
      bottom: 0;
      height: 100vh;
      border-left: 1px solid #eee;
      pointer-events: none;
    }
    .resize-bar-vertical:hover ~ .resize-line-vertical,
    .resize-bar-vertical:active ~ .resize-line-vertical {
      border-left: 1px solid #eee;
    }
    .resize-bar-vertical::-webkit-scrollbar {
      height: 100vh;
    }
    .left-top-content {
      position: absolute;
      top: 0;
      right: 5px;
      bottom: 0;
      left: 0;
      padding: 24px 24px;
      overflow-x: hidden;
      overflow-y: auto;
      display: flex;
      flex-direction: column;
      height: 100%;
      ::-webkit-scrollbar {
        width: 0;
      }
      .search-input {
        position: absolute;
        top: 0px;
        left: 0px;
        width: 100%;
      }
      .filter-tree {
        position: absolute;
        top: 48px;
        overflow: auto;
        height: calc(100% - 48px);
        width: 100%;
      }
    }
  }
  .right-container {
    flex-grow: 1;
    width: calc(100% - 300px);
  }
}
</style>
